#!/usr/bin/env python
# -*- coding: utf-8 -*-

from core.utils.singleton import singleton
from core.ide.commandmanager import CommandManager
import fnmatch
import shutil

@singleton
class LangsManager:
    def __init__(self):
        self.langs=[]
        CommandManager().listener("run",self.onRun)
        CommandManager().listener("build",self.onBuild)
    
    def addLang(self,lang):
        self.langs.append(lang)
        
        
    def getLang(self,name,forceLower=False):
        if len(self.langs):
            for lang in self.langs:
                if forceLower and lang.name.lower()==name:
                    return lang
                if lang.name==name:
                    return lang
        return None

    def getLangFromFile(self,path):
        if len(self.langs):
            for lang in self.langs:
                for filename in lang.getSourceFileNames():
                    if(fnmatch.fnmatch(path, filename)):
                        return lang
        return None
    
    def getOptions(self):
        pass
    
    def onRun(self):
        pass
    
    def onBuild(self):
        pass
    
    def getTemplatesList(self):
        ret=["blank.txt"]
        langDef=None
        try:
            type_=CommandManager().listener("get_projectType")
            langDef=self.getLang(type_)
            ret+=langDef.getTemplates()
            pass
        except:
            pass
        
        for lang in self.langs:
            if lang!=langDef:
                ret+=lang.getTemplates()
        
        return ret
    
    def createTemple(self,path,template):
        if template=="blank.txt":
            open(path,'w+')
        else:
            shutil.copyfile("extensions/langs/"+template, path)
    
    def destroy(self):
        for lang in self.langs:
            if hasattr(lang,"isReady") and lang.isReady():
                lang.stop()
                
                
    

class ContextDescription(object):
    def __init__(self):
        self.level=0
        self.name=""
        self.childs={}
        self.parent=None
        self.type=None
        self.doc=""
    
    def getDoc(self):
        return self.doc
        
    def addChild(self,child):
        self.childs[child.name]=child
        child.parent=self    
        
    def getChilds(self):
        return self.childs.values()
    
    def getChild(self,name):
        if self.childs.has_key(name):
            return self.childs[name]
        else:
            return None
        
        
class ContextError:
    def __init__(self,line,message):
        self.line=line
        self.message=message
        pass